<template>
  <div class="container">
    <div class="top">
      <div class="header_left">
        <a href="">小米商城</a>
        <a href="">MUI</a>
        <a href="">云服务</a>
        <a href="">协议规则</a>
      </div>
      <div class="header_right">
        <span v-if="isLogin" class="logout" @click="logout">登出</span>
        <span v-if="isLogin" class="login"><router-link :to="{ name: 'order' }">我的订单</router-link></span>
        <span v-if="!isLogin" class="login"><router-link :to="{name: 'login'}">登录</router-link></span>
        <span v-else>{{username}}</span>
        <span class="shop_car" @click="goShopCar"><span class="icon-cart"></span>购物车({{carCount}})</span>
      </div>
    </div>
  </div>
</template>

<script>
import { getStorage, setStorage } from '../../storage'
import { mapState } from 'vuex'
import request from '../../request'

export default {
  name: "navheader",
  data() {
   return {
      isLogin: false,
      username: ''
   }
  },
  computed: {
    ...mapState({
      carCount: state => state.carCount,
    })
  },
  mounted() {
    this.username = getStorage('userInfo', 'username');
    this.isLogin = !!this.username;

    if (this.isLogin) {
      request.get('/order/getCarCount')
        .then(({ data }) => {
          this.$store.dispatch('saveCarCount', data.carCount)
        })
    }

  },
  methods: {
    logout() {
      setStorage('userInfo');
      this.$store.dispatch('saveCarCount', 0)
      this.$router.push('/login');
    },
    goShopCar() {
      this.$router.push({ name: 'shopCar' })
    }
  }
};
</script>

<style lang="scss" scoped>
  @import './../../assets/scss/mixin.scss';
.container {
  min-width: 1226px;
  margin: 0 auto;
  height: 40px;
  background: black;
  overflow: hidden;
  line-height: 40px;
  .top {
      width: 90%;
      margin: 0 auto;
    .header_left {
      float: left;
      > a {
        display: inline-block;
        padding: 0 10px;
        color: #fff;
      }
    }
    .header_right {
      float: right;
      color: #fff;
      > span {
        display: inline-block;
        padding: 0 10px;
      }
      .login {
        a {
          color: #fff;
        }
      }
      .logout {
        cursor: pointer;
      }
      .shop_car {
          background: orange;
          cursor: pointer;
          .icon-cart{
            @include bgImg(16px,12px,'/imgs/icon-cart-checked.png');
            margin-right:4px;
          }
          &:hover {
              background: orchid;
          }
      }
    }
  }
}
</style>